import BaseAction from '@/components/base/BaseAction';
import { useModal } from '@/components/base/BaseModal';
import BasePageFrame from '@/components/base/BasePageFrame';
import BaseTable from '@/components/base/BaseTable';
import { useRequest } from '@/utils/request';
import { formateDate } from '@/utils/time';
import { InsuranceOutlined, MinusCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { ActionType, ProColumns } from '@ant-design/pro-table';
import { DatePicker, Radio, Space, Tag, Tooltip } from 'antd';
import moment from 'moment';
import { useRef, useState } from 'react';
import { getList, stopPlan } from './api';
import MaintainPlanModal from './modals/MaintainPlanModal';

const Info = () => {
  const tableRef = useRef<ActionType>();
  const mainModal = useModal(MaintainPlanModal, {
    onSuccess() {
      tableRef.current?.reload();
    }
  });
  const [searchInfo, setSearchInfo] = useState<{
    ensureDateStart?: string;
    ensureDateEnd?: string;
    isUrgent?: 0 | 1 | 2;
  }>({});
  const stop = useRequest(stopPlan, {
    manual: true,
    fetchKey: (id) => id,
    onSuccess() {
      tableRef.current?.reload();
    }
  });
  return (
    <BasePageFrame>
      <BaseTable
        rowKey='id'
        actionRef={tableRef}
        toolBarRender={() => [
          <DatePicker.RangePicker
            placeholder={['请选择保障时间段', '请选择保障时间段']}
            showTime={{ format: 'HH:mm:ss' }}
            format='YYYY-MM-DD HH:mm:ss'
            ranges={{
              今天: [moment().startOf('day'), moment().endOf('day')],
              本月: [moment().startOf('month'), moment().endOf('month')]
            }}
            onChange={(values, dateStrings) => {
              const [ensureDateStart, ensureDateEnd] = dateStrings;
              setSearchInfo({
                ...searchInfo,
                ensureDateStart,
                ensureDateEnd
              });
            }}
          />,
          <Radio.Group
            defaultValue={searchInfo.isUrgent}
            optionType='button'
            options={[
              { label: '全部', value: undefined as any },
              { label: '紧急', value: 2 },
              { label: '普通', value: 1 },
              { label: '正常', value: 0 }
            ]}
            onChange={(e) => {
              setSearchInfo({
                ...searchInfo,
                isUrgent: e.target.value
              });
            }}
          />
        ]}
        params={searchInfo}
        request={getList}
        columns={
          [
            {
              dataIndex: 'radarName',
              title: '雷达'
            },
            {
              title: '所属结构',
              render: (text, record) => {
                const { systemName, extensionName, keyPartsModelName } = record;
                return [systemName, extensionName, keyPartsModelName].filter((i) => i).join('-');
              }
            },
            {
              dataIndex: 'ensureName',
              title: '保障基础信息'
            },
            {
              dataIndex: 'ensureTypeName',
              title: '保障类型'
            },
            {
              dataIndex: 'cycle',
              title: '保障周期',
              renderText: (text) => {
                const date = formateDate(text, 2);
                return date.value ? `${date.value} ${date.unit}` : undefined;
              }
            },
            {
              dataIndex: 'isUrgent',
              title: (
                <>
                  保障状态
                  <Tooltip
                    placement='top'
                    overlayStyle={{ maxWidth: 320 }}
                    title={
                      <>
                        <div>
                          <Tag color='success'>正常</Tag> 距离下一次保障时间大于 <b>2</b> 天
                        </div>
                        <div style={{ margin: '8px 0' }}>
                          <Tag color='red'>紧急</Tag> 距离下一次保障时间小于 <b>1</b> 天
                        </div>
                        <div>
                          <Tag color='warning'>普通</Tag> 距离下一次保障时间大于 <b>1</b> 天 ，小于
                          <b>2</b>天
                        </div>
                        <div>如没有上次保障时间，便从创建时间开始计算下一次保障时间</div>
                      </>
                    }
                  >
                    <QuestionCircleOutlined style={{ marginLeft: 4 }} />
                  </Tooltip>
                </>
              ),
              render: (text) => {
                if (text === 0) {
                  return <Tag color='success'>正常</Tag>;
                }
                if (text === 1) {
                  return <Tag color='warning'>普通</Tag>;
                }
                if (text === 2) {
                  return <Tag color='red'>紧急</Tag>;
                }
                return '-';
              }
            },
            {
              dataIndex: 'ensureDate',
              title: '上次保障时间',
              valueType: 'dateTime'
            },
            {
              dataIndex: 'ensureDate',
              title: '预计下次保障时间',
              valueType: 'dateTime',
              renderText: (dom, record) => {
                if (record.isUrgent === -1) {
                  return undefined;
                }
                return moment(record.ensureDate ?? record.createDateTime).add(record.cycle, 's');
              }
            },
            {
              dataIndex: 'createDateTime',
              title: '创建时间',
              valueType: 'dateTime'
            },
            {
              dataIndex: 'status',
              title: '启用状态',
              render: (text) => {
                if (text === 1) {
                  return <Tag color='success'>启用</Tag>;
                }
                if (text === 0) {
                  return <Tag color='warning'>停用</Tag>;
                }
                return null;
              }
            },
            {
              title: '操作',
              fixed: 'right',
              render(text, record) {
                return (
                  record.status === 1 && (
                    <Space>
                      <BaseAction
                        color='green'
                        title='保障'
                        code='maintain'
                        icon={<InsuranceOutlined />}
                        onClick={() => {
                          mainModal.load({
                            id: record.id,
                            ensureDate: record.ensureDate,
                            keyPartsId: record.keyPartsId,
                            ensureId: record.ensureId
                          });
                        }}
                      />
                      <BaseAction
                        color='red'
                        title='停用'
                        code='maintain'
                        icon={<MinusCircleOutlined />}
                        loading={stop.fetches[record.id]?.loading}
                        onClick={() => {
                          stop.run(record.id);
                        }}
                      />
                    </Space>
                  )
                );
              }
            }
          ] as ProColumns[]
        }
      />
    </BasePageFrame>
  );
};

export default Info;
